/*
 * User: rant
 * Date: 06/02/2007
 *
 *
 */
package laMalinche.rete.nodes;

//import com.laMalinche.common.log.Log;
//import com.laMalinche.common.log.LogService;

import java.util.*;

/**
 *
 */
public abstract class BasicRelevantListener extends BasicReteNode implements Relevant {
//	private static final Log log = LogService.getLog(BasicRelevantListener.class);
	private final List<Relevant> relevantList = new ArrayList<Relevant>(2);

//	private int relevancyCounter = 0;

	public boolean isRelevant() {
//		return (relevancyCounter != 0);
		if (relevantList.isEmpty()) {
            return true;
        }
		boolean relevant = false;
		for (Relevant basicRelevant : relevantList) {
			if (basicRelevant.isRelevant() && !Boolean.FALSE.equals(basicRelevant.isConditionMet())) {
				relevant = true;
				break;
			}
		}
		return relevant;
	}

	public void addRelvantListener(BasicRelevantListener listener) {
		relevantList.add(listener);
		addWorkingMemoryListener(listener);
	}

	/**
	 a condition is irelevant if change will not affect any activator
	 */
	public void relveancyChanged(final boolean relevant) {
//		 final int oldCounter = relevancyCounter;
//		final Boolean conditionMet = isConditionMet();
//		if(relevant){
//			relevancyCounter = oldCounter+1;
//		} else{
//			relevancyCounter = oldCounter - 1;
//		}
////		relevancyCounter = (relevant) ? relevancyCounter + 1 : relevancyCounter - 1;
//		if (relevancyCounter < 0) {
//			log.error(this + "relevancyCounter value is" + relevancyCounter + "something is wrong with the relevant algoritm");
//		}
//		if (relevancyCounter > getWorkingMemoryListeners().size()) {
//			log.error(this + "relevancyCounter value is" + relevancyCounter + "something is wrong with the relevant algoritm");
//		}
//		if (oldCounter == 0 || relevancyCounter == 0) {
//			if (!Boolean.FALSE.equals(conditionMet)) {
//				informChangeRelevancy(relevant);
//			}
//		}
		informChangeRelevancy(relevant);
	}

	public List<Relevant> getRelevantList() {
		return relevantList;
	}

	protected abstract void informChangeRelevancy(final boolean relevant);
}